<?php
/**
 * Created by PhpStorm.
 * User: zhan
 * Date: 2019/1/12  15:41
 */
namespace app\api\logic;
use app\api\BaseModel;
use think\Db;

class Line extends  BaseModel
{
    /*
   * 线路 列表
   */
    public function lists()
    {
        $page=isset($this->requestData['page'])?$this->requestData['page']:'1';
        $limit=isset($this->requestData['limit'])?$this->requestData['limit']:'10';
        $where = array();
        $where['shop_id']=$this->user['shopid'];
        $count = db('route')->where($where)->count();
        $data = db('route')->where($where)->order('id desc')->page($page,$limit)->select();
//		var_dump($data);
        foreach($data as $key=>&$value){
            $address = db('route_address')->where('route_sn = '."'".$value['route_sn']."'")->column('address');
            $value['address'] = implode('-',$address);
        }
        $result['list'] = $data;
        $data['count'] = $count;
        $data['page_num']=$page;
        $data['page_limit']=$limit;
        return $result;
    }

    /*
     * 线路编辑
     */
    public function edit()
    {
//		var_dump($id);
        $where['shop_id']=$this->user['shopid'];
        $id = $this->requestData['id'];
        if (isset($this->requestData['id']) && !empty($this->requestData['id'])){
            if($id){
                $where['id']=$id;
                $route = db('route')->where($where)->find();
                if(empty($route))return array("message"=>'数据不存在');
            }
        }
        Db::startTrans();
        try {
//            die('1');
            if (!isset($this->requestData['specs'])) {
                throw new \Exception('specs参数必传');
            }else{
                $specs = json_decode($this->requestData['specs'], 1);
                if (!empty($specs) && is_array($specs)) {

                    $is_empty_specs = $this->is_empty_specs($specs);

                    if ($is_empty_specs) {
                        throw new \Exception('地址参数有空值');
                    }

                    if (!empty($id)) {
                        $route_sn = db('route')->where($where)->value('route_sn');
                    } else {
                        $route_sn = $this->becomerouteNo();
                        $route['route_sn'] = $route_sn;
                        $route['shop_id'] = $this->user['shopid'];
                        $result = db('route')->insert($route);
                        $id = db('route')->getLastInsID();
                    }

                    $data = [];
                    foreach ($specs as $key => &$value) {
                        $data[$key]['address'] = $value['address'];
                        $data[$key]['lng'] = $value['lng'];
                        $data[$key]['lat'] = $value['lat'];
                        $data[$key]['num'] = $value['num'];
                        $data[$key]['route_sn'] = $route_sn;
                        $data[$key]['route_id'] = $id;
                    }
//var_dump($data);
//			die;
                    if (!empty($id)) {
                        //修改，先删除旧数据，再添加新数据
                        $route_a = db('route_address')->where(['route_id' => $id])->find();
                        if (empty($route_a)) {
                            $result = 1;
                        } else {
                            $result = db('route_address')->where(['route_id' => $id])->delete();
                        }
                        if ($result) {
                            $res = db('route_address')->insertAll($data);
                        }

                    } else {
                        //添加
                        if ($result) {
                            $res = db('route_address')->insertAll($data);
                        };

                    }
                    if (!isset($res) || !$result) throw new \Exception('修改失败');
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return array("message"=>$e->getMessage());
        }
    }

    /*
   * 线路编辑
   */
    public function editname()
    {
        $id = isset($this->requestData['id'])?$this->requestData['id']:'0';
        $name = isset($this->requestData['name'])?$this->requestData['name']:'';
        if(empty($name))return array("message"=>'name参数必传');
        if(!$id)return array("message"=>'数据不存在');
        $where['id'] = $id;
        $where['shop_id']=$this->user['shopid'];
        $info = db('route')->where($where)->find();
        if(!$info) return ['message'=>'不存在该线路'];
        $data['route_sn'] = $name;
        $res = db('route')->where(['id'=>$id])->update($data);
//			var_dump($data);die;
        if(!$res) return ['message'=>'编辑失败'];

    }

    /*
     * 线路详情
     */
    public function info()
    {
        $id = isset($this->requestData['id'])?$this->requestData['id']:'0';
        if(!$id)return array("message"=>'数据不存在');
        $where['id'] = $id;
        $where['shop_id']=$this->user['shopid'];
        $info = db('route')->where($where)->find();
        if(!$info) return ['message'=>'不存在该线路'];
        $driver_id = $info['driver_id'];
        $address = db('route_address')->where(['route_id'=>$id])->column('address');
        $addressinfo = db('route_address')->where(['route_id'=>$id])->select();
        $data['address'] = implode('-',$address);

        $driver_shop['shop_id']=$this->user['shopid'];
        $driver_shop['status'] = 1;
        $driver_shop['isbind'] = 1;
        $driver = db("driver_shop")->where($where)->order("id desc")->select();
        foreach($driver as $key=>&$value){
            $value['driver'] = db('driver')->alias('d')
                ->where(['d.id'=>$value['driver_id']])
                ->field('d.sex,d.address,d.nickname,d.headimage,d.mobile')->find();
//            var_dump($value['driver']);die;
        }
        $result['info'] = $info;
        $result['info']['address'] = $address;
        $result['info']['addressinfo'] = $addressinfo;
        return $result;
    }

    /*
     * 设置线路时间
     */
    public function settime()
    {
        $id = isset($this->requestData['id'])?$this->requestData['id']:'0';
        if(!$id)return array("message"=>'数据不存在');
        $where['id'] = $id;
        $where['shop_id']=$this->user['shopid'];
        $info = db('route')->where($where)->find();
        if(!$info) return ['message'=>'不存在该线路'];

        $everyday = isset($this->requestData['everyday'])?$this->requestData['everyday']:'';//每隔几天
        $days = isset($this->requestData['day'])?$this->requestData['day']:'';//几号

//        $hour = isset($this->requestData['hour'])?$this->requestData['hour']:'';//每天几时
//        $min = isset($this->requestData['min'])?$this->requestData['min']:'';//每天几时
        if($everyday === false && empty($days))return ['message'=>'数据错误'];
        if($everyday && $days)return ['message'=>'间隔配送与几号配送只填一个'];
        $data=[];
//        die('a');
        if($everyday !== false || is_int($everyday)){
            $data['every_day'] = $everyday;
        }else {
            $data['every_day'] = 0;
        }

//			var_dump($id);die;
        if(empty($days)){
//				var_dump($days);die;
            $data['days'] = '';
        }else{
            if($this->is_not_month_day($days))return ['message'=>'几号送数据错误'];
            $data['days'] = $days;
        }

        $time = isset($this->requestData['time'])?$this->requestData['time']:'';

        if (!empty($time)) {
            $time = json_decode($time, 1);
            if (!empty($time) && is_array($time)) {

                $is_empty_time = $this->is_empty_time($time);

                if ($is_empty_time) {
                    return ['message' => '配送时间参数有空值'];
                }

                $everytime = [];
                foreach ($time as $key => &$val) {
                    $everytime[] = $val['time'] . ':' . '00';
                }
                if (!empty($everytime)) {
                    $data['every_time'] = serialize($everytime);
                } else {
                    $data['every_time'] = '';
                }
            }
        }else{
            $data['every_time'] = '';
        }

        $res = db('route')->where(['id'=>$id])->update($data);
//			var_dump($data);die;
        if(!$res) return ['message'=>'编辑失败'];
    }

    public function settimeInfo()
    {
        $id = isset($this->requestData['id'])?$this->requestData['id']:'0';
        if(!$id)return array("message"=>'数据不存在');
        $where['id'] = $id;
        $where['shop_id']=$this->user['shopid'];
        $info = db('route')->where($where)->find();
        if(!$info) return ['message'=>'不存在该线路'];

        $res = db('route')->where(['id'=>$id])->find();
        $times = [];
        if(!empty($res['every_time'])){
            $everytime = unserialize($res['every_time']);
            foreach($everytime as $k=>$v){
                $times[$k]['time'] = $v;
            }
            $res['every_time'] = $times;
        }else{
            $res['every_time'] = [];
        };
        $result['info'] = $res;
        return $result;
    }

    /*
     * 线路删除
     */
    public function routedel()
    {
        $id = $this->requestData['id'];
        if(!$id)return array("message"=>'数据不存在');
        $where['id'] = $id;
        $where['shop_id']=$this->user['shopid'];
        $info = db('route')->where($where)->find();
        if(!$info) return ['message'=>'不存在该线路'];
        Db::startTrans();
        try {

            $res = db('route')->where($where)->delete();

            $del = db('route_address')->where(['route_id'=>$id])->delete();
            if(!$del||!$res)throw new \Exception('删除失败');
            Db::commit();
        }catch (\Exception $e) {
            Db::rollback();
            return array("message"=>$e->getMessage());
        }
        return array();
    }

    /*
     * 设置司机
     */
    public function setRoutedriver()
    {
        $uid = $this->user['shopid'];
        $id = isset($this->requestData['id'])?$this->requestData['id']:'0';
        $driver_id = isset($this->requestData['driver_id'])?$this->requestData['driver_id']:'0';
        if(empty($id))return array("message"=>'id参数必传');
        if(empty($driver_id))return array("message"=>'driver_id参数必传');
        $driver = db('driver')->where(['id'=>$driver_id])->find();
        $driver_shop = db('driver_shop')->where(['driver_id'=>$driver_id,'shop_id'=>$uid,'status'=>1,'isbind'=>1])->find();
        if(empty($driver)||empty($driver_shop))return array("message"=>'id非法');
        $where['id'] = $id;
        $where['shop_id']=$this->user['shopid'];
        $info = db('route')->where($where)->find();
        if(!$info) return ['message'=>'不存在该线路'];
        if($info['driver_id'] == $driver_id)return ['message'=>'该司机已绑定'];
        $data['driver_id'] = $driver_id;
        $res = db('route')->where(['id'=>$id])->update($data);
        if(!$res) return ['message'=>'编辑失败'];
    }

    //设置司机时的可选司机列表
    public function Routedriver()
    {
        $where['shop_id']=$this->user['shopid'];
        $where['status'] = 1;
        $where['isbind'] = 1;
        $list = db("driver_shop")->where($where)->order("id desc")->select();
        foreach($list as $key=>&$value){
            $value['driver'] = db('driver')->alias('d')
                ->where(['d.id'=>$value['driver_id']])
                ->field('d.sex,d.address,d.nickname,d.headimage,d.mobile')->find();
        }
        $result['list'] = $list;
        return $result;
    }

    public static function becomerouteNo()
    {
        $yearCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $routeSn =
            $yearCode[intval(date('Y')) - 2017] . time();
        return $routeSn;
    }


    /*
    *检测商品规格是否有空值
    */
    public function is_empty_specs($specs){
        $is_empty_specs = false;
        foreach($specs as $v){
            if(empty($v['address']) || empty($v['lng']) || empty($v['lat']) || empty($v['num']))
            {
                $is_empty_specs = true;
                break;
            }
        }

        return $is_empty_specs;
    }
    /*
    *检测商品规格是否有空值
    */
    public function is_empty_time($specs){
        $is_empty_time = false;
        foreach($specs as $v){
            if(empty($v['time']))
            {
                $is_empty_time = true;
                break;
            }
        }

        return $is_empty_time;
    }

    /*
     * 检测号数
     */
    public function is_not_month_day($days)
    {
        $is_month_day = false;
        if(strpos($days,',')){
            $days = implode(',', $days);
            foreach($days as $v){
                if(is_int($v)||in_array($v,[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31]))
                {
                    $is_month_day = true;
                    break;
                }
            }
        }

        return $is_month_day;
    }

}